<template>
    <div>
        <el-drawer title="账户安全" :with-header="false" :visible.sync="isShow" custom-class="drawer_safe" :before-close="visibleChange">
            <div class="safe_title">账户安全</div>
            <div class="safe_t">
                <div class="safe_t_l">
                    <img src="@/assets/svg/zhaq_icon5.svg" width="100" />
                </div>
                <div class="safe_t_r">
                    <div>安全等级：一般</div>
                    <div>您与安全达人的距离一步之遥</div>
                </div>
            </div>
            <div class="safe_b">
                <el-row :gutter="20">
                    <el-col :span='8'>
                        <div class="safe_b_item">
                            <i class="iconfont icon-weibiaoti-5-01" style="font-size:44px;color:#3399FF;padding:50px 0"></i>
                            <div>手机号</div>
                            <div></div>
                            <div>{{personForm.phone|toTel}}</div>
                            <el-button @click="openSave('修改手机号')">修改手机号</el-button>
                        </div>
                    </el-col>
                    <el-col :span='8'>
                        <div class="safe_b_item">
                            <i class="iconfont icon-weibiaoti-5-02" style="font-size:44px;color:#3399FF;padding:50px 0"></i>
                            <div>登录密码</div>
                            <div></div>
                            <div>定期更换密码有助于账号安全</div>
                            <el-button @click="openSave('修改登录密码')">修改登录密码</el-button>
                        </div>
                    </el-col>
                    <el-col :span='8'>
                        <div class="safe_b_item">
                            <i class="iconfont icon-weibiaoti-5-03" style="font-size:44px;color:#3399FF;padding:50px 0"></i>
                            <div>邮箱</div>
                            <div></div>
                            <div>{{personForm.email|toMail}}</div>
                            <el-button @click="openSave('修改邮箱')">修改邮箱</el-button>
                        </div>
                    </el-col>

                </el-row>
            </div>
        </el-drawer>
        <el-dialog :title="title" :visible.sync="isOpen" width="30%" center>
            <el-form label-width="100px" :model="editform" ref="editform" label-position="left" :rules="rules">
                <el-form-item v-if="title=='修改手机号'" label="手机号" prop="phone" :rules="[{required: true,pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,message: '请输入正确的手机号',trigger: 'blur' }]">
                    <el-input v-model="editform.phone" :autofocus="true" ref="phone"></el-input>
                </el-form-item>
                <el-form-item v-if="title=='修改登录密码'" label="登录密码" prop="oldPassword" :rules="[{required: true,trigger: 'blur',message:'请输入当前登录密码' }]">
                    <el-input type="password" autocomplete="off" v-model="editform.oldPassword" :autofocus="true" ref="oldPassword"></el-input>
                </el-form-item>
                <el-form-item v-if="title=='修改登录密码'" label="新登录密码" prop="newPassword" :rules="[{required: true,trigger: 'blur',message:'请输入新密码' }, { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }]">
                    <el-input type="password" autocomplete="off" v-model="editform.newPassword"></el-input>
                </el-form-item>
                <el-form-item v-if="title=='修改登录密码'" label="确认密码" prop="checkPass">
                    <el-input type="password" autocomplete="off" v-model="editform.checkPass"></el-input>
                </el-form-item>
                <el-form-item v-if="title=='修改邮箱'" label="邮箱" prop="email" :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
                    <el-input v-model="editform.email" :autofocus="true" ref="email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isOpen = false">取 消</el-button>
                <el-button type="primary" @click="save('editform')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="提示" :visible.sync="isSure" width="30%" center :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
            <span>密码已修改请重新登录</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="sure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { JSEncrypt } from 'jsencrypt'
export default {
    props: {
        isShow: {
            type: Boolean,
            default: false,
        },
    },
    watch: {
        isShow: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.getPersonInfo()
                }
            },
        },
    },
    filters: { //过滤器的配置项
        toTel(str) {
            if (str) {
                let start = str.slice(0, 3);
                let end = str.slice(-3);
                return `${start}*****${end}`;
            }
        },
        toMail(str) {
            if (str) {
                let start = str.slice(0, 1);
                let end = str.slice(4);
                return `${start}******${end}`;
            }

        },
    },
    data() {
        let validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.editform.newPassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            personForm: {},
            title: '',
            isOpen: false,
            isSure: false,
            editform: {},
            publicKey: "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZo+eRHci5jxBX5Ia7UqFST41bWsPda7u243vdFLxpPxEMHHvZEb76Xv1dHuajiBWCbenG3nU8OgAqZAQxF+bid40mXs45+TZAEHPoHB9m6ICqWry/GRlftd22F+TZLrQURGlyRdBV5nM8rJ4qUOkwRdO+XEupIuhBdngJYzRTZwIDAQAB",
            rules: {
                checkPass: [{
                    required: true,
                    trigger: 'blur',
                    message: '请再次输入密码'
                },
                {
                    validator: validatePass,
                    trigger: 'blur'
                }
                ],
            }
        }
    },
    methods: {
        visibleChange() {
            this.$emit('visibleChange')
        },
        getPersonInfo() {
            this.$http
                .get(
                    `/${this.$ServiceName}/api/external/sysuser/${this.$version}/getuserdetailed`
                )
                .then((res) => {
                    if (res.data.code != '0000') {
                        return this.$message.error(res.data.msg)
                    }
                    this.personForm = res.data.data

                })
        },
        openSave(title) {
            this.isOpen = true
            this.title = title
            this.$nextTick(() => {
                this.$refs["editform"].clearValidate();
                if (title == "修改手机号") {
                    this.$refs['phone'].focus();
                }
                if (title == "修改登录密码") {
                    this.$refs['oldPassword'].focus();
                }
                if (title == "修改邮箱") {
                    this.$refs['email'].focus();
                }
                this.editform = JSON.parse(JSON.stringify(this.personForm))
            })

        },
        //检验密码安全性函数
        checkpassword(accCount, password) {
            //扩展Sting函数
            String.prototype.hashCode = function () {
                let hash = 0, i, chr;
                if (this.length === 0) return hash;
                for (i = 0; i < this.length; i++) {
                    chr = this.charCodeAt(i);
                    hash = ((hash << 5) - hash) + chr;
                    hash |= 0; // Convert to 32bit integer
                }
                return hash;
            };
            //是否是正序连续
            function isPositiveContinuous(str1, str2) {
                if (str2.hashCode() - str1.hashCode() == 1) return true;
                return false;
            }
            //是否是反序连续
            function isReverseContinuous(str1, str2) {
                if (str2.hashCode() - str1.hashCode() == -1) return true;
                return false;
            }
            //密码是否是正序或反序连续4位及以上
            function isPasswordContinuous(pwd) {
                let count = 0;//正序次数
                let reverseCount = 0;//反序次数
                let strArr = pwd.split("");
                for (let i = 0; i < strArr.length - 1; i++) {//从1开始是因为划分数组时，第一个为空
                    if (isPositiveContinuous(strArr[i], strArr[i + 1])) {
                        count++;
                    }
                    else {
                        count = 0;
                    }
                    if (isReverseContinuous(strArr[i], strArr[i + 1])) {
                        reverseCount++;
                    }
                    else {
                        reverseCount = 0;
                    }
                    if (count >= 2 || reverseCount >= 2) break;
                }
                if (count >= 2 || reverseCount >= 2) return false;
                return true
            }
            //不能纯数字或字母
            function isAllNumOrStr(password) {
                let allNum = /^\d+$/;
                let allStr = /^[A-Za-z]+$/
                if (allNum.test(password) || allStr.test(password)) {
                    return false;
                } else {
                    return true;
                }
            }
            //账号密码相同
            function isAccNoLikePwd(accCount, password) {
                if (accCount == password) {
                    return false
                } else {
                    return true
                }
            }
            let passwordContinuous = isPasswordContinuous(password)
            let allNumOrStr = isAllNumOrStr(password)
            let accNoLikePwd = isAccNoLikePwd(accCount, password)
            return [passwordContinuous, allNumOrStr, accNoLikePwd];
        },
        //密码加密方法
			encrypt(key, oldPwd) {
				let encrypt = new JSEncrypt();
				encrypt.setPublicKey(key);
				let encrypted = encrypt.encrypt(oldPwd);
				return encrypted;
			},
        save(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let [passwordContinuous, allNumOrStr, accNoLikePwd] = this.checkpassword(sessionStorage.getItem('accNo'), this.editform.newPassword)
                    if (!passwordContinuous && !allNumOrStr) {
                        const h = this.$createElement;
                        return this.$message({
                            message: h("div", {style:{color:'#f56c6c'}}, [
                                h("div", null, `密码连续3位不能为字典序`),
                                h("div", null, `密码不能为纯数字或纯字母`),
                            ]),
                            type: "error",
                        });
                    }
                    if (!passwordContinuous) {
                        return this.$message.error('密码连续3位不能为字典序')
                    }
                    if (!allNumOrStr) {
                        return this.$message.error('密码不能为纯数字或纯字母')
                    }
                    if (!accNoLikePwd) {
                        return this.$message.error('密码不能和账号相同')
                    }
                    let url;
                    let para;
                    if (this.title == '修改手机号') {
                        url = `/${this.$ServiceName}/api/external/sysuser/${this.$version}/updatephone`
                        para = {
                            phone: this.editform.phone
                        }
                    } else if (this.title == '修改登录密码') {
                        url = `/${this.$ServiceName}/api/external/sysaccount/v1/updatepassword`
                        para = {
                            oldPassword: this.encrypt(this.publicKey, this.editform.oldPassword),
                            newPassword: this.encrypt(this.publicKey, this.editform.newPassword),
                            // oldPassword: this.$md5(this.editform.oldPassword),
                            // newPassword: this.$md5(this.editform.newPassword),
                        }
                    } else if (this.title == '修改邮箱') {
                        url = `/${this.$ServiceName}/api/external/sysuser/${this.$version}/updateemail`
                        para = {
                            email: this.editform.email
                        }
                    }
                    this.$http.put(`${url}`, para)
                        .then(res => {
                            if (res.data.code != '0000') {
                                return this.$message.error(res.data.msg)
                            }
                            this.$message.success(res.data.msg);
                            this.isOpen = false;
                            this.getPersonInfo();
                            if (this.title == '修改登录密码') {
                                this.isSure = true
                            }
                        });
                } else {
                    return false;
                }
            });
        },
        sure() {
            this.$router.push({
                path: 'login'
            })
            sessionStorage.clear()
        }

    },
}
</script>

<style lang="less" scoped>
/deep/ .drawer_safe {
    width: 1080px !important;

    .el-drawer__body {
        background: #f5f7fa;
        overflow: auto;
    }

    .safe_title {
        background: #f5f7fa;
        border: 1px solid #e1e4eb;
        height: 40px;
        display: flex;
        align-items: center;
        padding-left: 20px;
    }

    .safe_t {
        margin: 20px;
        background: #fff;
        height: 240px;
        display: flex;
        justify-content: center;
        align-items: center;

        .safe_t_r {
            margin-left: 15px;

            div:nth-child(1) {
                font-size: 20px;
                color: #303133;
                letter-spacing: 0;
            }

            div:nth-child(2) {
                font-size: 14px;
                color: #606266;
                letter-spacing: 0;
                margin-top: 8px;
            }
        }
    }

    .safe_b {
        margin: 0 20px;
        padding-bottom: 20px;

        .safe_b_item {
            height: 360px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: #fff;

            div {
                width: 100%;
            }

            div:nth-child(2) {
                font-size: 18px;
                color: #333333;
                letter-spacing: 0;
                text-align: center;
                line-height: 18px;
            }

            div:nth-child(3) {
                width: 30px;
                height: 3px;
                background: #0099ff;
                border-radius: 3px;
                margin: 20px 0;
            }

            div:nth-child(4) {
                font-size: 14px;
                color: #909399;
                letter-spacing: 0;
                text-align: center;
                line-height: 18px;
            }

            .el-button {
                margin: 30px 0 55px 0;
            }
        }
    }
}
</style>
